<template>
  <div class="report-chat-session-list">
    <!-- 新建对话按钮 -->
    <div class="create-session-btn">
      <el-button
        class="create-new-btn"
        type="plain"
        @click="handleCreateNew"
        size="small"
      >
        <el-icon><Plus /></el-icon>
        新建对话
      </el-button>
    </div>

    <!-- 历史对话标题和清空按钮 -->
    <div class="session-header">
      <div class="header-left">
        <img src="@/assets/images/ai/homePage/history@2x.png" alt="" class="history-icon" />
        <span>历史对话</span>
      </div>
      <el-button
        :disabled="sessionGroups.length === 0"
        type="text"
        @click="handleClearAll"
        size="small"
        class="clear-btn"
      >
        清空
      </el-button>
    </div>

    <!-- 会话列表 -->
    <div class="session-list" v-loading="isLoading">
      <div v-for="group in sessionGroups" :key="group.date" class="session-group">
        <div class="group-date">{{ group.date }}</div>
        <div
          v-for="session in group.data"
          :key="session.id"
          class="session-item"
          :class="{ active: selectedSessionId === session.id }"
          @click="handleSessionClick(session)"
        >
          <div class="session-title">{{ session.title }}</div>
          <el-button
            type="text"
            size="mini"
            class="delete-btn"
            @click.stop="handleDeleteSession(session.id)"
          >
            <el-icon><Delete /></el-icon>
          </el-button>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="!isLoading && sessionGroups.length === 0" class="empty-state">
        <p>暂无历史对话</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Delete } from '@element-plus/icons-vue';
import type { ChatSessionVo } from '@/api/chat/types';
import { useChatStore } from '@/stores/modules/chat';

interface Props {
  selectedSessionId?: number | null;
}

interface Emits {
  (e: 'session-select', session: ChatSessionVo): void;
  (e: 'create-new'): void;
  (e: 'session-updated'): void;
}

const props = withDefaults(defineProps<Props>(), {
  selectedSessionId: null
});

const emit = defineEmits<Emits>();

const chatStore = useChatStore();
const isLoading = ref(false);

// 计算属性：会话分组
const sessionGroups = computed(() => chatStore.sessionGroups);

// 处理新建对话
const handleCreateNew = () => {
  emit('create-new');
};

// 处理会话点击
const handleSessionClick = (session: ChatSessionVo) => {
  emit('session-select', session);
};

// 处理删除单个会话
const handleDeleteSession = async (sessionId: number) => {
  try {
    await ElMessageBox.confirm(
      '此操作将永久删除该会话，是否继续？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    const success = await chatStore.deleteSession([sessionId]);
    if (success) {
      ElMessage.success('删除成功');
      emit('session-updated');
    } else {
      ElMessage.error('删除失败');
    }
  } catch (error) {
    // 用户取消删除
    console.log('用户取消删除');
  }
};

// 处理清空所有会话
const handleClearAll = async () => {
  try {
    await ElMessageBox.confirm(
      '此操作将永久删除所有会话，是否继续？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    const allSessionIds = chatStore.sessionList.map(session => session.id);
    const success = await chatStore.deleteSession(allSessionIds);
    if (success) {
      ElMessage.success('清空成功');
      emit('session-updated');
    } else {
      ElMessage.error('清空失败');
    }
  } catch (error) {
    // 用户取消清空
    console.log('用户取消清空');
  }
};

// 加载会话列表
const loadSessions = async () => {
  isLoading.value = true;
  try {
    await chatStore.requestSessionList();
  } catch (error) {
    console.error('加载会话列表失败:', error);
    ElMessage.error('加载会话列表失败');
  } finally {
    isLoading.value = false;
  }
};

// 组件挂载时加载数据
onMounted(() => {
  loadSessions();
});

// 暴露刷新方法
defineExpose({
  refresh: loadSessions
});
</script>

<style scoped lang="scss">
.report-chat-session-list {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 16px;
  background: #f8f9fa;
  .create-session-btn {
    margin-bottom: 16px;
    .create-new-btn {
      width: 100%;
      height: 36px;
      font-size: 14px;
      color: #333333;
      background: #ffffff;
      border: 1px solid #d9d9d9;
      border-radius: 6px;
      &:hover {
        color: #409eff;
        border-color: #409eff;
      }
    }
  }
  .session-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 4px;
    margin-bottom: 12px;
    .header-left {
      display: flex;
      gap: 8px;
      align-items: center;
      font-size: 14px;
      font-weight: 500;
      color: #333333;
      .history-icon {
        width: 16px;
        height: 16px;
      }
    }
    .clear-btn {
      padding: 0;
      font-size: 12px;
      color: #787b81;
      &:hover:not(:disabled) {
        color: #409eff;
      }
    }
  }
  .session-list {
    flex: 1;
    overflow-y: auto;
    .session-group {
      margin-bottom: 16px;
      .group-date {
        padding: 0 4px;
        margin-bottom: 8px;
        font-size: 12px;
        color: #999999;
      }
      .session-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 8px 12px;
        margin-bottom: 4px;
        cursor: pointer;
        background: #ffffff;
        border: 1px solid transparent;
        border-radius: 6px;
        transition: all 0.2s;
        &:hover {
          background: #f0f9ff;
          border-color: #e1f5fe;
        }
        &.active {
          background: #e3f2fd;
          border-color: #409eff;
        }
        .session-title {
          flex: 1;
          margin-right: 8px;
          overflow: hidden;
          text-overflow: ellipsis;
          font-size: 14px;
          color: #333333;
          white-space: nowrap;
        }
        .delete-btn {
          padding: 4px;
          color: #999999;
          opacity: 0;
          transition: opacity 0.2s;
          &:hover {
            color: #f56c6c;
          }
        }
        &:hover .delete-btn {
          opacity: 1;
        }
      }
    }
    .empty-state {
      padding: 40px 20px;
      font-size: 14px;
      color: #999999;
      text-align: center;
    }
  }
}

// 滚动条样式
.session-list::-webkit-scrollbar {
  width: 4px;
}
.session-list::-webkit-scrollbar-track {
  background: transparent;
}
.session-list::-webkit-scrollbar-thumb {
  background: #d9d9d9;
  border-radius: 2px;
}
.session-list::-webkit-scrollbar-thumb:hover {
  background: #bfbfbf;
}
</style>
